<template>
  <div>
    <el-dialog :visible.sync="isShow" width="500px" class="submit" :show-close="false">
      <div slot="title" class="title">用户注册</div>
      <el-form :model="form" label-width="70px" :rules="rules" ref="form">
        <el-form-item label="头像" class="upImg" prop="avatar">
          <el-upload
            class="avatar-uploader"
            action="http://127.0.0.1/heimamm/public/uploads"
            name="image"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.avatar" :src="baseUrl+'/'+imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="昵称" prop="username">
          <el-input v-model="form.username "></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email "></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="form.phone "></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password "></el-input>
        </el-form-item>
        <el-form-item label="图形码 " prop="code">
          <el-row>
            <el-col :span="15">
              <el-input v-model="form.code "></el-input>
            </el-col>
            <el-col :span="8" :offset="1">
              <img :src="baseUrl+codeImg" @click="refleshCode" alt class="codeImg" />
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="验证码" prop="rcode">
          <el-row>
            <el-col :span="13">
              <el-input v-model="form.rcode "></el-input>
            </el-col>
            <el-col :span="10" :offset="1">
              <el-button style="width:100% " @click="getRcode" :disabled="totalTime!=5">
                获取用户验证码
                <span v-if="totalTime!=5">{{totalTime}}s</span>
              </el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <div slot="footer" class="footer">
        <el-button type="primary" @click="submit">确定</el-button>
        <el-button @click="isShow=false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {getPhoneCode,toRegister} from '@/api/register.js'
export default {
  // 监听器watch
  watch:{
    //内部是一个函数
    //值发生变化给的时候执行该方法,类似于以前的change事件
    'isShow'(newVal){
      if(newVal== false){
        this.$refs.form.resetFields()
      }
    }
  },
  data() {
    return {
      // 倒计时时间
      totalTime:5,
      form: {
        avatar: "",
        username: "", //是	string	用户名
        email: "", //是	string	邮箱
        phone: "", //是	string	手机号
        password: "", //是	string	密码
        code: "", //是	string	头像地址
        rcode: "" //是	string	验证码
      },
      rules: {
        avatar: [{ required: true, message: "请上传头像", trigger: "blur" }],
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入正确的邮箱", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              const _reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
              if (_reg.test(value)) {
                callback();
              } else {
                callback(new Error("请输入正确的邮箱"));
              }
            }
          }
        ],
        phone: [
          { required: true, message: "'请正确输入手机号", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              const _reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
              if (_reg.test(value)) {
                callback();
              } else {
                callback(new Error("请正确输入手机号"));
              }
            }
          }
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        code: [{ required: true, message: "请输入图形码", trigger: "blur" }],
        rcode: [{ required: true, message: "请输入验证码", trigger: "blur" }]
      },
      isShow: false,
      imageUrl: "",
      baseUrl: process.env.VUE_APP_URL,
      codeImg: "/captcha?type=sendsms"
    };
  },
  methods: {
    getRcode() {
      let num = 0;
      this.$refs.form.validateField(["phone", "code"], err => {
        if (!err) {
          num++;
        }
       
      });
       if (num == 2) {
          // num++;
          // this.$axios({
          //   url:'/sendsms',
          //   method:'post',
          //   data:{
          //     code:this.form.code,
          //     phone:this.form.phone
          //   }
          this.totalTime--
          let timeID= setInterval(()=>{
             this.totalTime--
             if(this.totalTime==0){
               this.totalTime=5
               clearInterval(timeID)
             }
           },1000)
          getPhoneCode({
              code:this.form.code,
              phone:this.form.phone
            }) .then(res=>{
            console.log(res);

              this.$message.success(res.data.data.captcha+'')
            
          })
        } else {
          this.$message.error("请先输入手机号还有图形码");
        }
    },
    refleshCode() {
      this.codeImg = "/captcha?type=sendsms" + "&aaa=" + Math.random() * 999;
    },
    submit() {
      this.$refs.form.validate(result => {
        if (result) {
          toRegister(this.form).then(res=>{
            this.isShow = false
          this.$message.success("注册成功");
          console.log(res);
          
          })
        } else {
          this.$message.error("验证失败");
        }
      });
    },
    handleAvatarSuccess(res) {
      // this.imageUrl = URL.createObjectURL(file.raw);
      this.imageUrl = res.data.file_path;
      this.form.avatar = res.data.file_path;
      this.$refs.form.validateField(["avatar"]);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    }
  }
};
</script>
<style lang="less">
.submit {
  .codeImg {
    height: 40px;
    width: 100%;
  }
  .upImg {
    text-align: center;
  }
  .title {
    background: linear-gradient(to right, #01c5fa, #1394fa);
    font-size: 14px;
    font-family: Microsoft YaHei Regular, Microsoft YaHei Regular-Regular;
    font-weight: 400;
    text-align: center;
    color: #fefefe;
    letter-spacing: 0px;
    height: 46px;
    line-height: 46px;
  }
  .el-dialog__header {
    padding: 0;
  }
  .footer {
    text-align: center;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>